package com.lxy.cxcyxmmsbackend.sys.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;

public class JwtUtil {
    //秘钥
    public static final String sale = "220412";

    //把需要放入的数据放入到token
    public static String getToken(String username) {
        //设置超时时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 60 * 60 * 2);

        JWTCreator.Builder builder = JWT.create();
        //加密生成token
        String token = builder
                .withClaim("username", username)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(sale));
        //获取加密后的token
        return token;
    }

    //解析token，获取加密前字符串
    public static String getUserName(String token) {
        Verification verification = JWT.require(Algorithm.HMAC256(sale));
        JWTVerifier jwtVerifier = verification.build();
        DecodedJWT verify;
        try {
            verify = jwtVerifier.verify(token);
            Claim username = verify.getClaim("username");
            return username.asString();
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            throw e;
        }
    }

    //校验token
    public static boolean verifyToken(String token) {
        Verification verification = JWT.require(Algorithm.HMAC256(sale));
        JWTVerifier jwtVerifier = verification.build();

        try {
            //解密token 如果传入的token 无法解析或者超时 报错
            jwtVerifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }

    }
}
